package com.gears_software.sxdc.dccx.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.ICPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.IVehicleFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.CPOrderModel;
import com.gears_software.sxdc.dccx.data.model.LineInfoModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.VehicleModel;
import com.gears_software.sxdc.dccx.data.model.request.RCPOrderModel;
import com.gears_software.sxdc.dccx.ui.event.UpdateDriverTripEvent;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.gears_software.sxdc.dccx.ui.util.ShowSeat;
import com.gears_software.sxdc.dccx.ui.util.ShowTime;
import com.github.mzule.activityrouter.annotation.Router;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by SunMuran on 2017/7/26.
 * 发布行程页面
 */


@EActivity(R.layout.activity_release_schedule)
//@Router(value = "releasetrip/:title/:flag", isEActivity = true)
public class ReleaseScheduleActivity extends Activity {
    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;

    @ViewById
    TextView right_icon;
    @ViewById
    TextView tv_direction_icon;
    @ViewById
    TextView tv_plate_number_icon;
    @ViewById
    TextView tv_seat_icon;
    @ViewById
    TextView tv_univalence_icon;
    @ViewById
    TextView tv_date;
    @ViewById
    TextView tv_direction;
    @ViewById
    RelativeLayout rl_direction;
    @ViewById
    RelativeLayout rl_plate_number;
    @ViewById
    RelativeLayout rl_seat;
    @ViewById
    RelativeLayout rl_univalence;
    @ViewById
    TextView tv_plate_number;
    @ViewById
    TextView tv_seat;
    @ViewById
    TextView tv_univalence;
    @ViewById
    CheckBox checkbox;
    @ViewById
    Button btn_release_schedule;
    @ViewById
    TextView back_icon;
    @ViewById
    EditText et_xingshiluxian;
    @RestService
    ICPOrderFinder icpOrderFinder;
    @RestService
    IVehicleFinder vehicleFinder;
    @Bean
    GearsErrorHandler errorHandler;
    @Extra
    CPOrderModel orderModel;
    @Bean
    OttoBus bus;
    @Extra
    String title;
    @Extra
    String flag;
    @Extra
    int position;

    private OptionsPickerView pvLinePiceView, pvJiaGePickView, pvVehiclePickView;
    List<LineInfoModel> lineList = new ArrayList<LineInfoModel>();
    List<String> jiageList = new ArrayList<String>();
    List<VehicleModel> vehicleModelList = new ArrayList<VehicleModel>();
    ShowTime showTime = new ShowTime();
    ShowSeat showSeat = new ShowSeat();
    Context context;
    //线路id
    String lineid;
    //线路正反向
    String direction;
    //车辆id
    String vehicleId;

    @AfterViews
    void created() {
        context = this;
        actionbar_title.setText(title);
        initIconfont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        icpOrderFinder.setRestErrorHandler(errorHandler);
        vehicleFinder.setRestErrorHandler(errorHandler);

        showTime.initTimePicker(this, tv_date);
        showSeat.initSeat(this, tv_seat);
        if (flag.equals("update")) {
            if (orderModel != null) {
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                tv_date.setText(sf.format(orderModel.getDeparttime()));
                tv_direction.setText(orderModel.getStartpoint() + " 到 " + orderModel.getEndpoint());
                et_xingshiluxian.setText(orderModel.getRoute());
                tv_plate_number.setText(orderModel.getCarmodel() + " " + orderModel.getVehicleno() + " " + orderModel.getVehiclecolor());
                tv_seat.setText(String.valueOf(orderModel.getPassengernum()));
                tv_univalence.setText(String.valueOf(orderModel.getPrice()));
                direction = orderModel.getTraveldirection();
                lineid = orderModel.getCarpoollineid();
                vehicleId = orderModel.getVehicleid();
                btn_release_schedule.setText("修改行程");
            }
        } else {
            btn_release_schedule.setText("发布行程");

        }
    }

    void initIconfont() {
        tv_direction_icon.setTypeface(app.iconfont);
        tv_plate_number_icon.setTypeface(app.iconfont);
        tv_seat_icon.setTypeface(app.iconfont);
        tv_univalence_icon.setTypeface(app.iconfont);
        back_icon.setTypeface(app.iconfont);
        back_icon.setText(R.string.back_icon);
        right_icon.setVisibility(View.GONE);

    }

    @Click
    void back_icon() {
        finish();
    }

    //选择时间
    @Click
    void tv_date() {
        showTime.show();
    }

    //选择路线
    @Click
    void rl_direction() {
        getLineInfoList();
    }

    @Background
    void getLineInfoList() {
        ResultModel<List<LineInfoModel>> result = icpOrderFinder.getLineInfoList();
        showLineResult(result);
    }

    @UiThread
    void showLineResult(ResultModel<List<LineInfoModel>> result) {
        if (result != null) {
            if (result.getErrno().equals("0")) {
                if (result.getData() != null) {
                    lineList = result.getData();
                    if (lineList != null && lineList.size() > 0) {
                        closeKeyboard();
                        pvLinePiceView = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                tv_direction.setText(lineList.get(options1).getPickerViewText());
                                lineid = lineList.get(options1).getId();
                                direction = String.valueOf(lineList.get(options1).getDirection());
                                String fee = lineList.get(options1).getFee();
                                getJiaGe(fee);
                            }
                        }).setLineSpacingMultiplier(2).build();
                        pvLinePiceView.setPicker(lineList);
                        pvLinePiceView.show();
                    }
                }
            }
        }

    }

    private void getJiaGe(String fee) {
        if (fee != null && !fee.equals("")) {
            String[] re_fee = fee.split(",");
            jiageList.clear();
            for (String str : re_fee) {
                jiageList.add(str);
            }
            if (jiageList != null && jiageList.size() > 0) {
                closeKeyboard();
                pvJiaGePickView = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        tv_univalence.setText(jiageList.get(options1));
                    }
                }).setLineSpacingMultiplier(2).build();
                pvJiaGePickView.setPicker(jiageList);
            }
        }
    }

    //车辆信息
    @Click
    void rl_plate_number() {
        getVehicleList();
    }

    @Background
    public void getVehicleList() {
        ResultModel<List<VehicleModel>> res = vehicleFinder.getVehicleList();
        Logger.d(res);
        showResult(res);
    }

    @UiThread
    void showResult(ResultModel<List<VehicleModel>> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                vehicleModelList = res.getData();
                if (vehicleModelList != null && vehicleModelList.size() > 0) {
                    closeKeyboard();
                    pvVehiclePickView = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            tv_plate_number.setText(vehicleModelList.get(options1).getPickerViewText());
                            vehicleId = vehicleModelList.get(options1).getId();
                        }
                    }).setLineSpacingMultiplier(2).build();
                    pvVehiclePickView.setPicker(vehicleModelList);
                    pvVehiclePickView.show();
                }
            }
        }
    }

    //座位数
    @Click
    void rl_seat() {
        closeKeyboard();
        showSeat.showSeat();
    }

    //单价
    @Click
    void rl_univalence() {
        if (flag.equals("add")) {
            if (jiageList == null || jiageList.size() == 0) {
                TastyToast.makeText(context, "请选择路线", app.SHORT, app.WARNING);
            } else {
                pvJiaGePickView.show();
            }
        } else {
            getLineById();
        }
    }

    @Background
    void getLineById() {
        ResultModel<LineInfoModel> res = icpOrderFinder.getLineInfoById(lineid);
        showLineByIdResult(res);
    }

    @UiThread
    void showLineByIdResult(ResultModel<LineInfoModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    LineInfoModel infoModel = res.getData();
                    String price = infoModel.getFee();
                    getJiaGe(price);
                }
                pvJiaGePickView.show();
            }
        }
    }

    @Click
    void btn_release_schedule() {
        if (tv_date.getText().toString().equals("")) {
            TastyToast.makeText(this, "请选择出发时间", app.SHORT, app.WARNING);
        } else if (tv_direction.getText().toString().equals("")) {
            TastyToast.makeText(this, "请选择出发线路", app.SHORT, app.WARNING);
        } else if (et_xingshiluxian.getText().toString().equals("")) {
            TastyToast.makeText(this, "请填写途经线路", app.SHORT, app.WARNING);
        } else if (tv_plate_number.getText().toString().equals("")) {
            TastyToast.makeText(this, "请选择车辆", app.SHORT, app.WARNING);
        } else if (tv_seat.getText().toString().equals("")) {
            TastyToast.makeText(this, "请选择座位数", app.SHORT, app.WARNING);
        } else if (tv_univalence.getText().toString().equals("")) {
            TastyToast.makeText(this, "请选择价格", app.SHORT, app.WARNING);
        } else if (!checkbox.isChecked()) {
            TastyToast.makeText(this, "请阅读协议和条款", app.SHORT, app.WARNING);
        } else {

            RCPOrderModel model = new RCPOrderModel();
            model.setLineId(lineid);
            model.setDeparttime(tv_date.getText().toString());
            model.setFee(tv_univalence.getText().toString());
            model.setPassengernum(tv_seat.getText().toString());
            model.setVehicleId(vehicleId);
            model.setTraveldirection(direction);
            model.setRoute(et_xingshiluxian.getText().toString());
            if (flag.equals("add")) {
                AddCPOrder(model);
            } else {
                updateCPOrder(orderModel.getId(), model);
            }

        }

    }

    @Background
    void AddCPOrder(RCPOrderModel model) {
        ResultModel<String> result = icpOrderFinder.addCPOrder(model);
        showReleaseResult(result);
    }

    @UiThread
    void showReleaseResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(context, "发布行程成功", app.SHORT, app.SUCCESS);
                setResult(2);
                finish();
            } else {
                TastyToast.makeText(context, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    @Background
    void updateCPOrder(String id, RCPOrderModel model) {
        ResultModel<CPOrderModel> res = icpOrderFinder.updateCPOrder(id, model);
        showUpdateResult(res);
    }

    @UiThread
    void showUpdateResult(ResultModel<CPOrderModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(context, "修改行程成功", app.SHORT, app.SUCCESS);
                if (res.getData() != null) {
                    CPOrderModel orderModel = res.getData();
                    bus.post(new UpdateDriverTripEvent(position, orderModel));
                }
                finish();
            } else {
                TastyToast.makeText(context, "修改行程失败", app.SHORT, app.ERROR);
            }
        }
    }

    private void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
